println(niceToMeetYou("zkai",21))
fun niceToMeetYou(name: String, age: Int): String {
return "Hi! My name is $name and I $age years old"
}
function取得String:name以及Integer:age
fun fun名(名稱:屬性,名稱:屬性): return結果的屬性println結果為 Hi! My name is zkai and I 21 years old
val example:Int
example = niceToMeetYou("zkai",21)
example為Integer,但是niceToMeetYou的function,return結果為String
此處會發生衝突
class SomeOne {
var name = "zkai"
var age = 21
}
val a = SomeOne()
val b = SomeOne()
println("${a.age}, ${a.name}")
b.age = 50
b.name = "hahahaha"
println("${b.age}, ${b.name}")
SomeOne的Class中有name和age
在a.b變數創建一個SomeOne時
都有各自的name和age
於是b都會被修改過println結果為 21, zkai 50, hahahaha
class SomeOne(var name: String, var age: Int) {
constructor(name: String) : this(name, 0)
constructor(yearOfBirth: Int, name: String)
: this(name, 2020 - yearOfBirth)
}
val a = SomeOne(1997,"zkai")
val b = SomeOne("zkai")
println("${a.age}, ${a.name}")
println("${b.age}, ${b.name}")
Class一樣可以設定接取值 Class SomeOne(var 名稱:屬性,var 名稱:屬性)
constructor設定其中一項只接取字串的名字 SomeOne("zkai") , this(name, 0) 將age設為0
另外一項 SomeOne(1997,"zkai") 接取年份和名稱 , this(name, 2020 - yearOfBirth) 用2020減去年份println結果為 21, zkai 0, zkai